{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "import psycopg2\n",
    "import pandas as pd\n",
    "import requests\n",
    "from IPython.display import display\n",
    "sys.path.insert(0, os.path.realpath('..'))\n",
    "import django\n",
    "django.setup()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Overview\n",
    "\n",
    "Get a list of stations, pull the response zones from geo.firecares.org, convert to shapefiles and merge into a single shapefile: `/tmp/outf.shp`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stations = FireStation.objects.filter(state='TN', department__name__contains='Memphis')\n",
    "print stations.count()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "host = \"\"\"https://geo.firecares.org/?\"\"\"\n",
    "\n",
    "qs = {\n",
    "    'f': 'kmz',\n",
    "    'Facilities': {\n",
    "        'features': [\n",
    "            {\n",
    "                'geometry': {\n",
    "                    'x': -90.0455557969999,\n",
    "                    'y': 35.15284569100004,\n",
    "                    'spatialReference': {\n",
    "                        'wkid': 4326\n",
    "                    }\n",
    "                },\n",
    "            }\n",
    "        ],\n",
    "        'geometryType': 'esriGeometryPoint'\n",
    "    },\n",
    "    'env:outSR': 4326,\n",
    "    'text_input': '4,4,4',\n",
    "    'Break_Values': '4 6 8',\n",
    "    'returnZ': False,\n",
    "    'returnM': False\n",
    "}\n",
    "\n",
    "from firecares.firestation.models import FireStation\n",
    "import urllib\n",
    "import copy\n",
    "print stations.count()\n",
    "files = []\n",
    "\n",
    "for fs in stations:\n",
    "    q = copy.deepcopy(qs)\n",
    "    q['Facilities']['features'][0]['geometry']['x'] = fs.geom.x\n",
    "    q['Facilities']['features'][0]['geometry']['y'] = fs.geom.y\n",
    "    print '{}{}'.format(host, q)\n",
    "    url = host + urllib.urlencode(q)\n",
    "    resp = requests.get(url)\n",
    "    fname = '/tmp/{}.kmz'.format(fs.id)\n",
    "    tmp_shp = '/tmp/{}.shp'.format(fs.id)\n",
    "    files.append(tmp_shp)\n",
    "    with open(fname, 'w') as f:\n",
    "        f.write(resp.content)  \n",
    "    !ogr2ogr -f \"ESRI Shapefile\" {tmp_shp} {fname} -dim 2\n",
    "    !ogrinfo /tmp/{fs.id}.shp -sql 'alter table \"{fs.id}\" add column fc_id integer'\n",
    "    !ogrinfo /tmp/{fs.id}.shp -dialect SQLite -sql 'update \"{fs.id}\" set fc_id = {fs.id}'\n",
    "    !ogrinfo /tmp/{fs.id}.shp -sql 'alter table \"{fs.id}\" add column dept_fdid character(5)'\n",
    "    !ogrinfo /tmp/{fs.id}.shp -dialect SQLite -sql \"update \\\"{fs.id}\\\" set dept_fdid = '{fs.department.fdid}'\"\n",
    "    !ogrinfo /tmp/{fs.id}.shp -sql 'alter table \"{fs.id}\" add column st_name character(254)'\n",
    "    !ogrinfo /tmp/{fs.id}.shp -dialect SQLite -sql \"update \\\"{fs.id}\\\" set st_name = '{fs.name}'\"\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ogr2ogr /tmp/outf.shp {files[0]}\n",
    "\n",
    "for f in files[1:]:\n",
    "    !ogr2ogr -update -append /tmp/outf.shp {f}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ogrinfo /tmp/outf.shp -al"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
